<?php
namespace app\index\controller;

use app\index\model\CompanyModel;
use app\index\model\EnginBaoModel;
use app\index\model\EnginFoldModel;
use app\index\model\FileModel;
use app\index\model\UserModel;
use app\index\service\PiaoService;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\Request;
class Upload extends Common
{
    protected $movePath = '../infoasset';
    protected $importPath = './importtmp';

    public function upload_file()
    {
        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($this->cominfo['capacity'] > 0){
                if( $this->cominfo['capacity'] - $this->cominfo['havecap'] <= $filesize){
                    throw new Exception("系统存储空间不足");
                }
            }

            $info = $file->validate([
                'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
            ])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = FileModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                CompanyModel::where(['id'=>$this->userinfo['comid']])->setInc('havecap', $filesize);

                $return_data = $ins;
                $return_data['id'] = $ins_id;
                $return_data['created_user_name'] =  $this->userinfo['realname'];
                $return_data['encpath'] = $encpath;
                unset($return_data['oripath']);
            }else{
                throw new Exception("上传失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }

    public function upload_engin_file(Request $request)
    {
        $param = $request->param();

        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($this->cominfo['capacity'] > 0){
                if( $this->cominfo['capacity'] - $this->cominfo['havecap'] <= $filesize){
                    throw new Exception("系统存储空间不足");
                }
            }

            $info = $file->validate([
                'size'=>Config::get('service.upload.size'),'ext'=>Config::get('service.upload.ext')
            ])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['pid'] = $param['pid'];
                $ins['enginid'] = $param['enginid'];
                $ins['type'] = 1;
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = EnginFoldModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(EnginFoldModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                CompanyModel::where(['id'=>$this->userinfo['comid']])->setInc('havecap', $filesize);

                $return_data = $ins;
                $return_data['id'] = $ins_id;
                $return_data['created_user_name'] =  $this->userinfo['realname'];
                $return_data['encpath'] = $encpath;
                unset($return_data['oripath']);
            }else{
                throw new Exception("上传失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }

    public function upload_piaoshou_file(Request $request)
    {
        $param = $request->param();

        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($this->cominfo['capacity'] > 0){
                if( $this->cominfo['capacity'] - $this->cominfo['havecap'] <= $filesize){
                    throw new Exception("系统存储空间不足");
                }
            }

            $info = $file->validate([
                'size'=>Config::get('service.upload.size'),'ext'=>'jpg,jpeg,png,pneg'
            ])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = FileModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                CompanyModel::where(['id'=>$this->userinfo['comid']])->setInc('havecap', $filesize);

                $return_file = $ins;
                $return_file['id'] = $ins_id;
                $return_file['created_user_name'] =  $this->userinfo['realname'];
                $return_file['encpath'] = $encpath;
                unset($return_file['oripath']);
                $return_data['fileinfo'] = $return_file;


                $piaoPath = Config::get('service.img_url').str_replace('../infoasset','',$ins['oripath']);
                $piaores = (new PiaoService())->get_piaoshou_trip_info($piaoPath);
                if($piaores['code'] == 2000){
                    $return_data['piaoinfo'] = $piaores['data'];
                }else{
                    throw new Exception("发票识别失败");
                }
            }else{
                throw new Exception("发票识别失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }
    public function upload_piaokai_file(Request $request)
    {
        $param = $request->param();

        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($this->cominfo['capacity'] > 0){
                if( $this->cominfo['capacity'] - $this->cominfo['havecap'] <= $filesize){
                    throw new Exception("系统存储空间不足");
                }
            }

            $info = $file->validate([
                'size'=>Config::get('service.upload.size'),'ext'=>'jpg,jpeg,png,pneg'
            ])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = FileModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                CompanyModel::where(['id'=>$this->userinfo['comid']])->setInc('havecap', $filesize);

                $return_file = $ins;
                $return_file['id'] = $ins_id;
                $return_file['created_user_name'] =  $this->userinfo['realname'];
                $return_file['encpath'] = $encpath;
                unset($return_file['oripath']);
                $return_data['fileinfo'] = $return_file;


                $piaoPath = Config::get('service.img_url').str_replace('../infoasset','',$ins['oripath']);
                $piaores = (new PiaoService())->get_piaokai_trip_info($piaoPath);
                if($piaores['code'] == 2000){
                    $return_data['piaoinfo'] = $piaores['data'];
                }else{
                    throw new Exception("发票识别失败");
                }
            }else{
                throw new Exception("发票识别失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }

    public function upload_avatar(Request $request)
    {
        $type = $request->param('type', '', 'string');
        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($filesize > 1024){
                throw new Exception("文件大小不能超过1M");
            }

            $info = $file->validate(['ext'=>'jpg,jpeg,png,pneg'])->move($this->movePath);
            if($info){
                $ins = [];
                $ins['comid'] = $this->userinfo['comid'];
                $ins['name'] =  $fileInfo['name'];
                $ins['ext'] =  strtolower($info->getExtension());
                $ins['size'] = $filesize;
                $ins['oripath'] =  $this->movePath.'/'.str_replace('\\', '/', $info->getSaveName());
                $ins['created_user'] =  $this->userinfo['id'];
                $ins['created_at'] =  date('Y-m-d H:i:s');
                $ins_id = FileModel::insertGetId($ins);

                $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                if(FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]) === false){
                    throw new Exception("上传失败");
                }

                if($type == 'userinfo'){
                    UserModel::where(['id'=>$this->userinfo['id']])->update([
                        'avatar' => $encpath,
                        'avatar_id' => $ins_id,
                    ]);
                }

                $return_data['id'] = $ins_id;
                $return_data['encpath'] = $encpath;
            }else{
                throw new Exception("上传失败");
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000,lang('code_4000'), $return_data);
        }
        return outputJson(2000,lang('code_2000'), $return_data);
    }

    public function upload_import()
    {
        $file = request()->file("file");
        try{
            $fileInfo = $file->getInfo();
            $filesize = round($fileInfo['size']/1024,2);
            if($filesize > 2028){
                throw new Exception("文件大小不能超过2M");
            }

            $shanName = $this->importPath.'/'.$this->userinfo['id'];
            if(file_exists($shanName.'.xls')){
                unlink($shanName.'.xls');
            }
            if(file_exists($shanName.'.xlsx')){
                unlink($shanName.'.xlsx');
            }

            $extArr = explode('.', $fileInfo['name']);
            $yuanExt = strtolower(end($extArr));
            if(!in_array($yuanExt, ['xls','xlsx'])){
                throw new Exception("请上传2M以内的（xls,xlsx）文件");
            }
            $info = $file->validate(['ext'=>'xls,xlsx'])->move($this->importPath, $this->userinfo['id'].'.'.$yuanExt);
            if($info){
                $sheet = $this->get_excel_sheet($yuanExt);
            }else{
                throw new Exception("请上传2M以内的（xls,xlsx）文件");
            }
        }catch (\Exception $e){
            return outputJson(4000,$e->getMessage());
        }

        $data['name'] = $fileInfo['name'];
        $data['sheet'] = $sheet;
        $data['ext'] = $yuanExt;
        return outputJson(2000,lang('code_2000'), $data);
    }

    public function show_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = FileModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid'] || !file_exists($fileinfo['oripath'])){
            echo '';exit;
        }


        if($fileinfo['ext'] == 'pdf'){
            header('Content-type: application/pdf');
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }
        if(in_array($fileinfo['ext'], ['jpg','jpeg','png','pneg','gif'])){
            header( "Content-Type: image/jpg;image/jpeg;image/png;image/pneg;image/jif;");
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }

        if(in_array($fileinfo['ext'], ['doc','docx','xls','xlsx','ppt','pptx'])){
            $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
            return outputJson(2000,lang('code_2000'),$newPath);
        }

        echo '';exit;
    }

    public function show_bao_real_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = EnginBaoModel::where(['id'=>$fileid])->find();

        if (!$fileinfo ||!file_exists($fileinfo['oripath'])){
            echo '';exit;
        }

        if($fileinfo['ext'] == 'pdf'){
            $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
            return outputJson(2000,lang('code_2000'),$newPath);
        }
        if(in_array($fileinfo['ext'], ['jpg','jpeg','png','pneg','gif'])){
            header( "Content-Type: image/jpg;image/jpeg;image/png;image/pneg;image/jif;");
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }

        if(in_array($fileinfo['ext'], ['doc','docx','xls','xlsx','ppt','pptx'])){
            $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
            return outputJson(2000,lang('code_2000'),$newPath);
        }

        echo '';exit;
    }


    public function show_bao_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        if(!$fileid){
            $fileid = EnginBaoModel::where(['encpath'=>$dd])->value('id');
        }
        $fileinfo = EnginBaoModel::where(['id'=>$fileid])->find();

        if (!$fileinfo ||!file_exists($fileinfo['oripath'])){
            echo '';exit;
        }

        if($fileinfo['ext'] == 'pdf'){
            header('Content-type: application/pdf');
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }
        if(in_array($fileinfo['ext'], ['jpg','jpeg','png','pneg','gif'])){
            header( "Content-Type: image/jpg;image/jpeg;image/png;image/pneg;image/jif;");
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }

        if(in_array($fileinfo['ext'], ['doc','docx','xls','xlsx','ppt','pptx'])){
            $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
            return outputJson(2000,lang('code_2000'),$newPath);
        }

        echo '';exit;
    }

    public function show_engin_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = EnginFoldModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid'] || !file_exists($fileinfo['oripath'])){
            echo '';exit;
        }


        if($fileinfo['ext'] == 'pdf'){
            header('Content-type: application/pdf');
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }
        if(in_array($fileinfo['ext'], ['jpg','jpeg','png','pneg','gif'])){
            header( "Content-Type: image/jpg;image/jpeg;image/png;image/pneg;image/jif;");
            echo file_get_contents($fileinfo['oripath'],true);exit;
        }

        if(in_array($fileinfo['ext'], ['doc','docx','xls','xlsx','ppt','pptx'])){
            $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
            return outputJson(2000,lang('code_2000'),$newPath);
        }

        echo '';exit;
    }

    public function down_real_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = FileModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid']){
            throw new Exception('请求资源不存在');
        }
        $newPath = str_replace('../infoasset','',$fileinfo['oripath']);
        return outputJson(2000,lang('code_2000'),$newPath);
    }

    public function down_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = FileModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid']){
            throw new Exception('请求资源不存在');
        }
        $filename = $fileinfo['oripath'];
        if(file_exists($filename)){
            $file = fopen ( $filename, "rb" );
            Header ( "Content-type: application/octet-stream" );
            Header ( "Accept-Ranges: bytes" );
            Header ( "Accept-Length: " . filesize ( $filename ) );
            Header ( "Content-Disposition: attachment; filename=" . $fileinfo['name'] );
            ob_clean();
            flush();
            echo fread ( $file, filesize ( $filename ) );
            fclose ( $file );
            exit ();
        }else{
            throw new Exception('请求资源不存在');
        }
    }

    public function down_bao_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        if(!$fileid){
            $fileid = EnginBaoModel::where(['encpath'=>$dd])->value('id');
        }
        $fileinfo = EnginBaoModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid']){
            throw new Exception('请求资源不存在');
        }
        $filename = $fileinfo['oripath'];
        if(file_exists($filename)){
            $file = fopen ( $filename, "rb" );
            Header ( "Content-type: application/octet-stream" );
            Header ( "Accept-Ranges: bytes" );
            Header ( "Accept-Length: " . filesize ( $filename ) );
            Header ( "Content-Disposition: attachment; filename=" . $fileinfo['name'] );
            ob_clean();
            flush();
            echo fread ( $file, filesize ( $filename ) );
            fclose ( $file );
            exit ();
        }else{
            throw new Exception('请求资源不存在');
        }
    }

    public function down_engin_file(Request $request){
        $dd = $request->param('dd', '', 'string');
        $dd = str_replace('@','/', $dd);
        $fileid = encrypt($dd, 'D', Config::get('service.info_key'));
        $fileinfo = EnginFoldModel::where(['id'=>$fileid])->find();
        if (!$fileinfo || $fileinfo['comid'] != $this->userinfo['comid']){
            throw new Exception('请求资源不存在');
        }
        $filename = $fileinfo['oripath'];
        if(file_exists($filename)){
            $file = fopen ( $filename, "rb" );
            Header ( "Content-type: application/octet-stream" );
            Header ( "Accept-Ranges: bytes" );
            Header ( "Accept-Length: " . filesize ( $filename ) );
            Header ( "Content-Disposition: attachment; filename=" . $fileinfo['name'] );
            ob_clean();
            flush();
            echo fread ( $file, filesize ( $filename ) );
            fclose ( $file );
            exit ();
        }else{
            throw new Exception('请求资源不存在');
        }
    }

    public function get_excel_sheet($ext){
        require_once '../extend/phpoffice/PHPExcel/PHPExcel.php';
        $PHPExcel = new \PHPExcel();
        if($ext =='xlsx' ){
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel2007.php';
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }else{
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel5.php';
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }

        $PHPExcel = $PHPReader->load($this->importPath.'/'.$this->userinfo['id'].'.'.$ext);
        return $PHPExcel->getSheetNames();
    }

    public function get_excel_sheet_data($sheetid, $currentRow=1){
        require_once '../extend/phpoffice/PHPExcel/PHPExcel.php';
        $PHPExcel = new \PHPExcel();

        $ext ='xls';
        $dataName = $this->importPath.'/'.$this->userinfo['id'].'.xls';
        if(!file_exists($dataName)){
            $ext ='xlsx';
            $dataName = $this->importPath.'/'.$this->userinfo['id'].'.xlsx';
            if(!file_exists($dataName)){
                return [];
            }
        }


        if($ext =='xlsx' ){
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel2007.php';
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }else{
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel5.php';
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }



        //载入文件
        $PHPExcel = $PHPReader->load($this->importPath.'/'.$this->userinfo['id'].'.'.$ext);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet = $PHPExcel->getSheet($sheetid);
        //获取总列数
        $allColumn = $currentSheet->getHighestColumn();
        $allColumn = \PHPExcel_Cell::columnIndexFromString($allColumn);


        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
//dump($allRow);
//dump($allColumn);
//die;
        $columnHave = [];
        for ($currentRow; $currentRow <= $allRow; $currentRow++) {
            $rowHave = false;

            //从哪列开始，A表示第一列
            for ($currentColumn = 0; $currentColumn <= $allColumn; $currentColumn++) {
                $currentColumnString = \PHPExcel_Cell::stringFromColumnIndex($currentColumn);
                //数据坐标
                $address = $currentColumnString . $currentRow;
                //读取到的数据，保存到数组$data中
                $cell = $currentSheet->getCell($address)->getFormattedValue();
//                $cell = gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($cell));
                if ($cell instanceof PHPExcel_RichText) {
                    $cell = $cell->__toString();
                }
                $data[$currentRow - 1][$currentColumnString] = $cell;

                if(!isset($columnHave[$currentColumnString])){
                    $columnHave[$currentColumnString] = false;
                }
                if($cell){
                    $rowHave = true;
                    $columnHave[$currentColumnString] = true;
                }
            }
            if(!$rowHave){
                unset($data[$currentRow - 1]);
            }

        }
        foreach ($data as $kkk=>&$vvv){
            foreach ($vvv as $key=>&$value){
                if(!$columnHave[$key]){
                    unset($vvv[$key]);
                }
            }
        }
        return array_values($data);
    }

}